<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()">
      <el-form-item prop="name" label="名称">
        <el-input v-model="dataForm.name" placeholder="名称"></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
const emit = defineEmits(['refreshDataList']);
const visible = ref(false);
const dataFormRef = ref();
// 表单数据
const dataForm = reactive({
  id: '',
  name: '',
});
// 表单规则
const rules = ref({
  name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
});
// 初始化
const init = (id?: string, name?: string) => {
  visible.value = true;
  dataForm.id = '';
  dataForm.name = '';
  console.log(dataForm);
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  console.log(dataForm);
  if (id && name) {
    nextTick(() => getInfo(id, name));
  }
};

// 获取信息，因为信息很少，并且表格行中有数据，所以没有请求接口
const getInfo = (id: string, name: string) => {
  Object.assign(dataForm, {
    id,
    name,
  });
  console.log(dataForm);
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    // 模拟接口请求
    Promise.resolve(true).then((res) => {
      ElMessage.success({
        message: '成功',
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit('refreshDataList');
        },
      });
    });
  });
};

defineExpose({
  init,
});
</script>

<style lang="less"></style>
